<template>
    <AppPopup :modelValue="props.modelValue" type="bottom" @update:modelValue="close" :isMaskClick="props.isMaskClick">
        <view class="goods-sku">
            <image class="icon-close" src="@/static/logo.png" @click="close"></image>
            <view class="goods-sku-head">
                <view class="dir-left-nowrap goods-info">
                    <view class="thumb">
                        <AppImage :src="status.selectShop.goods_thumb ?? props.goodsInfo.goods_thumb"></AppImage>
                    </view>
                    <view class="info">
                        <view class="dir-left-nowrap cross-center money-box">
                            <view class="sign">￥</view>
                            <view class="money">{{ priceCom }}</view>
                        </view>
                        <view v-if="true">{{ status.selectArr.join(' ') }}</view>
                    </view>
                </view>
            </view>
            <view class="goods-sku-body">
                <view class="spec-item" v-for="(spec, index1) in status.specList" :key="index1">
                    <view class="dir-left-nowrap tit">
                        <view class="dir-left-nowrap box-grow-1">{{ spec.name }}</view>
                        <view class="dir-left-nowrap">
                            <image class="cross-center change-icon" src="@/static/logo.png"></image>
                            <view>大图</view>
                        </view>
                    </view>
                    <view class="dir-left-nowrap sku-list">
                        <view class="sku-item" :class="[false ? 'on' : '']" v-for="(item, index2) in spec.list" :key="index2"
                            @click="skuClick(item, index1, index2)">
                            {{ item.name }}</view>
                    </view>
                </view>
            </view>
        </view>
    </AppPopup>
</template>
            
<script setup lang='ts' name="AppGoodsSku">
import AppPopup from "@/components/AppPopup/index.vue";
import AppImage from "@/components/AppImage/index.vue";
import { tool } from "@/lib";
import { Goods, Sku, Spec, SpecItem } from "@/types/service/goods";

export interface AppGoodsSkuProps {
    /**组件显示 */
    modelValue: boolean
    /**商品信息 */
    goodsInfo: Goods
    /**允许点击遮罩关闭组件 默认允许 */
    isMaskClick?: boolean
    /**立即购买按钮的文字 */
    buyNowText?: string
    /**加入购物车按钮的文字 */
    addCartText?: string
    /**是否隐藏库存显示 */
    hideStock?: boolean
    /**默认选中规格 */
    defaultSelect?: object
    /**最小购买数量 */
    minBuyNum?: number
    /**最大购买数量 */
    maxBuyNum?: number
}
export interface AppGoodsSkuEmits {
    (e: 'update:modelValue', value: AppGoodsSkuProps['modelValue']): void
}

const props = withDefaults(defineProps<AppGoodsSkuProps>(), {
    isMaskClick: true,
    buyNowText: '立即购买',
    addCartText: '加入购物车',
    hideStock: false,
    minBuyNum: 1,
    maxBuyNum: 1000
})
const emit = defineEmits<AppGoodsSkuEmits>()

const close = () => {
    emit('update:modelValue', false)
}

type Status = {
    /**存放要和选中的值进行匹配的数据 */
    shopItemInfo: any
    /**存放最后选中的商品 */
    selectShop: any
    /**存放被选中的对象 */
    selectArr: string[]
    specList: Spec[],
    selectNum: number
}
const status = reactive<Status>({
    shopItemInfo: {},
    selectShop: {},
    selectArr: [],
    specList: [],
    selectNum: props.minBuyNum ?? 1
})


/**检查路径 */
const checkInpath = () => {
    const arr = props.goodsInfo.spec_list
    arr.forEach(group => {
        group.list.forEach(item => {
            if (status.shopItemInfo.hasOwnProperty(getArrayToSting(status.selectArr))) {
                item.isShow = true;
            } else {
                item.isShow = false;
            }
        })
    })
    status.specList = arr

}
onMounted(() => {
    checkItem()
    checkInpath()
})

/**规格按钮的点击事件 */
const skuClick = (value: SpecItem, index1: number, index2: number) => {
    if (status.selectArr[index1] && status.selectArr[index1] == value.name) {
        status.selectArr[index1] = value.name
    } else {
        status.selectArr[index1] = value.name
    }
    checkInpath();
    // 如果全部选完
    checkSelectGoods();
}

/**计算价格区间 */
const priceCom = computed(() => {
    let str = '';
    if (status.selectShop['id']) {
        str = tool.priceFilter(status.selectShop.price);
    } else {
        const skuList = props.goodsInfo['sku_list'];
        if (skuList && skuList.length > 0) {
            let valueArr: number[] = [];
            skuList.map((skuItem, index) => {
                valueArr.push(+skuItem.price);
            });
            const min = tool.priceFilter(Math.min(...valueArr));
            const max = tool.priceFilter(Math.max(...valueArr));
            if (min === max) {
                str = min + '';
            } else {
                str = `${min} - ${max}`;
            }
        }
    }
    return str;
})

/**检查规格对应商品 */
const checkSelectGoods = () => {
    if (status.selectArr.every(item => item != '')) {
        status.selectShop = status.shopItemInfo[getArrayToSting(status.selectArr)];
        // console.log(status.selectArr);
        // console.log(getArrayToSting(status.selectArr));
        // console.log(status.shopItemInfo[getArrayToSting(status.selectArr)]);
        return
        let stock = status.selectShop['stock'];
        if (typeof stock !== 'undefined' && status.selectNum > stock) {
            status.selectNum = stock;
        }
        if (status.selectNum > props.maxBuyNum) {
            status.selectNum = props.maxBuyNum;
        }
        if (status.selectNum < props.minBuyNum) {
            status.selectNum = props.minBuyNum;
        }
    } else {
        status.selectShop = {};
    }
}

/**计算sku里面规格形成路径(核心算法) */
const checkItem = () => {
    let originalSkuList = props.goodsInfo['sku_list'];
    let skuList: Sku[] = [];
    let stockNum = 0;
    originalSkuList.forEach((skuItem, index) => {
        if (+skuItem['stock'] > 0) {
            skuList.push(skuItem);
            stockNum += +skuItem['stock'];
        }
    });
    if (stockNum <= 0) {
        console.log('缺货');
        // that.outFoStock = true;
    }
    // 计算有多小种可选路径
    // console.log('skuList:', skuList);
    skuList.reduce(
        (arrs, items) => {
            return arrs.concat(
                items['sku_name_arr'].reduce(
                    (arr: any[], item) => {
                        return arr.concat(
                            arr.map(item2 => {
                                if (!status.shopItemInfo.hasOwnProperty(getArrayToSting([...item2, item]))) {
                                    status.shopItemInfo[getArrayToSting([...item2, item])] = items;
                                }
                                return [...item2, item];
                            })
                        );
                    },
                    [[]]
                )
            );
        },
        [[]]
    );
    // console.log(status.shopItemInfo);

}
const getArrayToSting = (arr: string[]) => {
    let str = '';
    arr.map((item, index) => {
        item = item.replace(/\./g, '。');
        if (index == 0) {
            str += item;
        } else {
            str += ',' + item;
        }
    });
    return str;
}
</script>

<style scoped lang="scss">
.goods-sku {
    position: relative;
    height: 1000rpx;

    .icon-close {
        position: absolute;
        top: 20rpx;
        right: 20rpx;
        width: 50rpx;
        height: 50rpx;
    }

    .goods-sku-head {
        padding: 20rpx;

        .goods-info {
            .thumb {
                $size: 120rpx;
                width: $size;
                height: $size;
                border-radius: 8rpx;
                overflow: hidden;
                margin-right: 20rpx;
            }

            .info {
                .money-box {
                    $textColor: red;
                    color: $textColor;
                    padding-top: 10rpx;

                    .sign {
                        font-size: 30rpx;
                    }

                    .money {
                        font-size: 40rpx;
                    }
                }
            }

        }
    }

    .goods-sku-body {
        padding: 20rpx;

        .spec-item {
            padding: 20rpx 0;
            border-top: 2rpx solid #ccc;

            .tit {
                font-size: 30rpx;
                font-weight: bold;
                padding-bottom: 20rpx;

                .change-icon {
                    width: 40rpx;
                    height: 40rpx;
                    margin-right: 10rpx;
                }
            }

            .sku-list {
                .sku-item {
                    position: relative;
                    margin-right: 20rpx;
                    padding: 2rpx 8rpx;
                    border-radius: 8rpx;
                    background: #f5f5f5;

                    &.on::before {
                        content: '';
                        position: absolute;
                        top: 0;
                        right: 0;
                        bottom: 0;
                        left: 0;
                        border: 2rpx solid red;
                    }
                }
            }
        }
    }
}
</style>